<?php
/**
 * Created by PhpStorm.
 * User: ysongyang
 * Date: 2016/6/6
 * Time: 11:59
 */
namespace Admin\Controller;
use Think\Controller;
use Org\Util\Rbac;
class LoginController extends Controller{

    public function index(){
        $this->display();
    }


    //生成验证码
    public function verify()
    {
        import('Class.Code',APP_PATH);
        $code = new \Code;
        $code->make();
    }


    //登录验证
    public function login()
    {
        $this->User = D('User');
        if (!$this->User->create()){
            // 如果创建失败 表示验证没有通过 输出错误提示信息
            $this->redirect(MODULE_NAME . '/Login/index',array('msg'=>$this->User->getError()));
        }else{
            import('Class.Code',APP_PATH);
            $code = new \Code;
            $_code = $code->get();
            if(strtoupper($_POST['code'])!=$_code){
                $this->redirect(MODULE_NAME . '/Login/index',array('msg'=>'验证码错误！'));
            }
            $password = md5(C('AUTH_CODE') . md5(I('password')));
            $where = array('username' => I('username'),'password' => $password);
            $data = array('logintime' => time(),'loginip' => get_client_ip());
            $user = $this->User->where($where)->find();
            if(!isset($user)){
                $this->redirect(MODULE_NAME . '/Login/index',array('msg'=>'用户名或密码错误！'));
            }
            if ($user['lock']==0) {
                $this->redirect(MODULE_NAME . '/Login/index',array('msg'=>'当前用户被锁定！'));
                //$this->success('当前用户被锁定！', U(MODULE_NAME . '/Login/logout'));
            } else {
                // 更新登录次数
                $this->User->where($where)->setInc('loginnum', 1);
                // 更新用户信息
                $this->User->where($where)->data($data)->save();
                session(C('USER_AUTH_KEY'),$user['id']);
                session('username',$user['username']);
                // 超级管理员识别
                if ($user['username'] == C('RBAC_SUPERADMIN')) {
                    session(C('ADMIN_AUTH_KEY'), true);
                }
                // 缓存访问权限
                Rbac::saveAccessList();
                $this->redirect(MODULE_NAME . '/Index/index');
            }
        }
    }

    public function logout()
    {
        session_unset();
        session_destroy();
        $this->redirect(MODULE_NAME . '/Login/index');
    }
}